<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="店员昵称" prop="nickname">
        <el-input v-model="formData.nickname" placeholder="请输入店员昵称" />
      </el-form-item>
      <el-form-item label="店员头像" prop="avatar">
		<UploadImg v-model="formData.avatar" height="100px" width="100px" :limit="1" :is-show-tip="false" />
      </el-form-item>
	  
	  <el-form-item label="店员等级" prop="workerClerkLevelId">
	  		<el-select v-model="formData.workerClerkLevelId" placeholder="请选择店员等级" clearable class="!w-240px">
	  		  <el-option v-for="level in levelOptions" :key="level.id" :label="level.name" :value="level.id">
	  		    <span class="flex items-center gap-x-8px">
	  		      <el-avatar :src="level.img" size="small" />
	  		      {{ level.name }}
	  		    </span>
	  		  </el-option>
	  		</el-select>
	  </el-form-item>
	  
	  
	  <el-form-item label="性别" prop="sex">
	    <el-radio-group v-model="formData.sex">
	      <el-radio
	        v-for="dict in getStrDictOptions(DICT_TYPE.MEMBER_SEX)"
	        :key="dict.value"
	        :value="dict.value"
	      >
	        {{ dict.label }}
	      </el-radio>
	    </el-radio-group>
	  </el-form-item>
      <el-form-item label="年龄" prop="age">
		<el-input-number v-model="formData.age" controls-position="right" :min="18" />
      </el-form-item>
      <el-form-item label="微信" prop="weixin">
        <el-input v-model="formData.weixin" placeholder="请输入微信" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-input v-model="formData.city" placeholder="请输入城市" />
      </el-form-item>
      <el-form-item label="相关经验" prop="experience">
        <el-input type="textarea" v-model="formData.experience" placeholder="请输入相关经验" />
      </el-form-item>
      <el-form-item label="上传录音" prop="sound">
		  <el-upload
		    ref="uploadRef"
		    v-model:file-list="fileList"
		    :action="uploadUrl"
		    :auto-upload="true"
		    :data="data"
		    :disabled="formLoading"
		    :limit="1"
		    :on-change="handleFileChange"
		    :on-error="submitFormError"
		    :on-exceed="handleExceed"
		    :on-success="submitFormSuccess"
		    :http-request="httpRequest"
		    accept=".mp3,.mp4,.m4a"
		    drag
		  >
		    <i class="el-icon-upload"></i>
		    <div class="el-upload__text"> 将文件拖到此处，或 <em>点击上传</em></div>
		    <template #tip>
		      <div class="el-upload__tip" style="color: red">
		        提示：仅允许导入 mp3、mp4、m4a 格式文件！
		      </div>
		    </template>
		  </el-upload>
      </el-form-item>
	  <el-form-item label="播放录音">
	    <view class="sound-play">
	    	<audio v-if="formData.sound!=''&&formData.sound!=null" :src="formData.sound" type="audio/wav"
	    		controls="controls"></audio>
	    	<span v-else>暂无语音</span>
	    </view>
	  </el-form-item>
      <el-form-item label="音频时长" prop="soundTime">
		<el-input-number v-model="formData.soundTime" controls-position="right" :min="5" />
	  </el-form-item>
      <el-form-item label="相册" prop="albums">
		<UploadImgs v-model="picUrls" height="100px" width="100px" :limit="6" />
      </el-form-item>
      <el-form-item label="介绍" prop="intro">
        <el-input type="textarea" v-model="formData.intro" placeholder="请输入介绍" />
      </el-form-item>
	  <el-form-item label="接单时间" prop="onlineTime">
	    <el-input v-model="formData.onlineTime" placeholder="请输入接单时间" />
	  </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { useUpload } from '@/components/UploadFile/src/useUpload'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { ClerkLevelApi, ClerkLevelVO } from '@/api/worker/clerklevel'
import { ClerkApplyApi, ClerkApplyVO } from '@/api/worker/clerkapply'

/** 店员申请 表单 */
defineOptions({ name: 'ClerkApplyForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  workerClerkId: undefined,
  userId: undefined,
  nickname: undefined,
  avatar: undefined,
  sex: undefined,
  age: undefined,
  weixin: undefined,
  mobile: undefined,
  city: undefined,
  experience: undefined,
  sound: undefined,
  soundType: undefined,
  soundTime: undefined,
  albums: undefined,
  intro: undefined,
  onlineTime: undefined,
  workerClerkLevelId: undefined,
  status: undefined,
})
const picUrls = ref([])
const formRules = reactive({
  userId: [{ required: true, message: '用户编号不能为空', trigger: 'blur' }],
  nickname: [{ required: true, message: '店员昵称不能为空', trigger: 'blur' }],
  avatar: [{ required: true, message: '店员头像不能为空', trigger: 'blur' }],
  workerClerkLevelId: [{ required: true, message: '店员等级不能为空', trigger: 'blur' }],
  sex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
  age: [{ required: true, message: '年龄不能为空', trigger: 'blur' }],
  weixin: [{ required: true, message: '微信不能为空', trigger: 'blur' }],
  mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
  city: [{ required: true, message: '城市不能为空', trigger: 'blur' }],
  soundTime: [{ required: true, message: '录音时长不能为空', trigger: 'blur' }],
  albums: [{ required: true, message: '相册不能为空', trigger: 'blur' }],
  intro: [{ required: true, message: '介绍不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const fileList = ref([])
const data = ref({ path: '' })
const uploadRef = ref()
const { uploadUrl, httpRequest } = useUpload()

const levelOptions = ref<ClerkLevelApi.ClerkLevelVO[]>([])

const getList = async () => {
  const data = await ClerkLevelApi.getClerkLevelList()
  levelOptions.value = data;
}

/** 处理上传的文件发生变化 */
const handleFileChange = (file) => {
  data.value.path = file.name
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}

const submitFormSuccess = (e) => {
  formData.value.sound = e.data;
  // 清理
  formLoading.value = false
  // 提示成功，并刷新
  message.success('上传成功')
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ClerkApplyApi.getClerkApply(id)
	  if(formData.value.albums){
		 picUrls.value =  formData.value.albums.split(',')
	  }
    } finally {
      formLoading.value = false
    }
  }
  
  getList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ClerkApplyVO
	if(picUrls.value.length < 1){
		message.error('请上传相册！')
		return;
	}
	data.albums = picUrls.value.join(',')
    if (formType.value === 'create') {
      await ClerkApplyApi.createClerkApply(data)
      message.success(t('common.createSuccess'))
    } else {
      await ClerkApplyApi.updateClerkApply(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    workerClerkId: undefined,
    userId: undefined,
    nickname: undefined,
    avatar: undefined,
    sex: undefined,
    age: undefined,
    weixin: undefined,
    mobile: undefined,
    city: undefined,
    experience: undefined,
    sound: undefined,
    soundType: undefined,
    soundTime: undefined,
    albums: undefined,
    intro: undefined,
	workerClerkLevelId: undefined,
	onlineTime: undefined,
    status: undefined,
  }
  formRef.value?.resetFields()
}
</script>
